package com.xieshue.im.handler.codec;

import com.xieshue.im.protocol.MessageProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 消息解码器
 *
 * @author xieshue
 * @date 2017\12\22 0022
 */
public class ImMessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in == null) {
            return;
        }
        if (in.readableBytes() < 4) {
            return;
        }
        int readableLength = in.readInt();
        byte[] body = new byte[readableLength];
        in.readBytes(body);
        MessageProto messageProto = MessageProto.parseFrom(body);
        out.add(messageProto);
    }
}
